package com.xiaouyudeguang.common.utils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

public class FreeMarkerUtils {

    private static Template getTemplate(String template_path, String templateFileName) {
        Configuration configuration = new Configuration();
        Template template = null;
        try {
            configuration.setDirectoryForTemplateLoading(new File(template_path));
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            configuration.setDefaultEncoding("UTF-8");   //设置编码
            //模板文件
            template = configuration.getTemplate(templateFileName + ".ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return template;
    }

    public static void genteratorFile(Map<String, String> input, String template_path, String templateFileName, String savePath, String fileName) throws IOException {
        genteratorFile(input, template_path, templateFileName, savePath, fileName, true);
    }

    public static void genteratorFile(Map<String, String> input, String template_path, String templateFileName, String savePath, String fileName, Boolean isCover) throws IOException {
        Template template = getTemplate(template_path, templateFileName);
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (new File(savePath + "/" + fileName).exists() && !isCover) {
            return;
        }
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(Files.newOutputStream(Paths.get(savePath + "/" + fileName)), StandardCharsets.UTF_8);
            template.process(input, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.flush();
    }

}